package com.soloyogame.anitoys.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class HttpClient {
	private Map parameters = new HashMap();
	private String url;
	private String sendEncode = "UTF-8";
	private String receiceEncode = "UTF-8";
	private static int BUFFER_SIZE = 8096; //缓冲区大小

	public void addParameter(String name, String value) {
		this.parameters.put(name, value);
	}
	public void setProxy(String host, String port) {
		System.getProperties().put("proxySet","true");   
        System.getProperties().setProperty("http.proxyHost",host);   
        System.getProperties().setProperty("http.proxyPort",port); 
	}
	public String post() throws Exception{
		String response="";
		try {
			response=this.send();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("PostFailure,Url:"+url, e);
		}
		return response;
	}
	public String get(String httpUrl,String encode) throws Exception{
		String html = "";
		try {
			//System.out.println("Http Access Url:" + httpUrl);
			URL url = new URL(httpUrl);
			URLConnection c = url.openConnection();
			InputStream inputs = c.getInputStream();
			int all = inputs.available();
			byte[] b = new byte[all];
			inputs.read(b);
			html = new String(b, encode);
			inputs.close();
		}

		catch (Exception e) {
			e.printStackTrace();
			throw new Exception("getFailure,Url:"+httpUrl);

		}
		String returnContent=html.toString();
		//System.out.println("Url return:\n" + returnContent);
		return returnContent;
	}

	/**
	 * 发送对帐请求，适用于返回xml的请求
	 * @return Document 结果
	 * @throws Exception 
	 * @throws Exception
	 */
	private String send() throws Exception {	
		String paramStr = "";
		Object[] services = parameters.keySet().toArray();
		StringBuffer rspContent = null;
		BufferedReader reader = null;
		DataInputStream in = null;
		URLConnection con;
		URL url; 
		String response;
		for (int i = 0; i < services.length; i++) {
			if (i == 0) {
				paramStr += services[i]
						+ "="
						+ URLEncoder.encode(parameters.get(services[i]).toString(), this.getSendEncode());
			} else {
				paramStr += "&"
						+ services[i]
						+ "="
						+ URLEncoder.encode(parameters.get(services[i]).toString(), this.getSendEncode());
			}
		}
		try {
			url = new URL(this.getUrl());
			con = url.openConnection();
			con.setUseCaches(false);
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setRequestProperty("Content-type","application/x-www-form-urlencoded");
			byte[] sendParamByte = paramStr.toString().getBytes("iso8859_1");
			con.setRequestProperty("Content-length", String.valueOf(sendParamByte.length));
			DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
			dataOut.write(sendParamByte);
			dataOut.flush();
			dataOut.close();
			rspContent = new StringBuffer();
			in = new DataInputStream(con.getInputStream());
			reader = new BufferedReader(new InputStreamReader(in, this.getReceiceEncode()));
			String aLine;
			while ((aLine = reader.readLine()) != null) {
				rspContent.append(aLine+"\n");
			}
			response = rspContent.toString();
			in.close();

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		 
		} finally {
			if (reader != null)
				reader.close();
			if (in != null)
				in.close();
		}
		return response;
	}
	
	public String sendStream(String content) throws Exception {
		String paramStr = URLEncoder.encode(content, this.getSendEncode());
		StringBuffer rspContent = null;
		BufferedReader reader = null;
		DataInputStream in = null;
		URLConnection con;
		URL url; 
		String response;
		try {
			url = new URL(this.getUrl());
			con = url.openConnection();
			con.setUseCaches(false);
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setRequestProperty("Content-type","application/x-www-form-urlencoded");
			byte[] sendParamByte = paramStr.toString().getBytes("iso8859_1");
			con.setRequestProperty("Content-length", String.valueOf(sendParamByte.length));
			con.setRequestProperty("Keep-alive", "false");
			
			DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
			dataOut.write(sendParamByte);
			dataOut.flush();
			dataOut.close();
			rspContent = new StringBuffer();
			in = new DataInputStream(con.getInputStream());
			reader = new BufferedReader(new InputStreamReader(in, this.getReceiceEncode()));
			String aLine;
			while ((aLine = reader.readLine()) != null) {
				rspContent.append(aLine+"\n");
			}
			response = rspContent.toString();
			in.close();

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		 
		} finally {
			if (reader != null)
				reader.close();
			if (in != null)
				in.close();
		}
		return response;
	}
	public String sendObjStream(Object content) throws Exception {
		StringBuffer rspContent = null;
		BufferedReader reader = null;
		DataInputStream in = null;
		URLConnection con;
		URL url; 
		String response;
		try {
			url = new URL(this.getUrl());
			con = url.openConnection();
			con.setUseCaches(false);
			con.setDoOutput(true);
			con.setDoInput(true);
			//con.setRequestProperty("Content-type","application/x-www-form-urlencoded");
			//byte[] sendParamByte = content.getBytes("iso8859_1");
			//con.setRequestProperty("Content-length", String.valueOf(sendParamByte.length));
			//con.setRequestProperty("Keep-alive", "false");
			
			//ObjectInputStream ins = new ObjectInputStream(in);
			ObjectOutputStream dataOut = new ObjectOutputStream(con.getOutputStream());
			dataOut.writeObject(content);
			//write(sendParamByte);
			dataOut.flush();
			dataOut.close();
			rspContent = new StringBuffer();
			in = new DataInputStream(con.getInputStream());
			reader = new BufferedReader(new InputStreamReader(in, this.getReceiceEncode()));
			String aLine;
			while ((aLine = reader.readLine()) != null) {
				rspContent.append(aLine+"\n");
			}
			response = rspContent.toString();
			in.close();

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		 
		} finally {
			if (reader != null)
				reader.close();
			if (in != null)
				in.close();
		}
		return response;
	}
	
	public void postAndDownFile(String fileSavePath) throws Exception{
		String paramStr = "";
		Object[] services = parameters.keySet().toArray();
		StringBuffer rspContent = null;
		BufferedReader reader = null;
		DataInputStream in = null;
		URLConnection con;
		URL url; 
		String response;
		for (int i = 0; i < services.length; i++) {
			if (i == 0) {
				paramStr += services[i]
						+ "="
						+ URLEncoder.encode(parameters.get(services[i]).toString(), this.getSendEncode());
			} else {
				paramStr += "&"
						+ services[i]
						+ "="
						+ URLEncoder.encode(parameters.get(services[i]).toString(), this.getSendEncode());
			}
		}
		try {
			url = new URL(this.getUrl());
			con = url.openConnection();
			con.setUseCaches(false);
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setRequestProperty("Content-type","application/x-www-form-urlencoded");
			byte[] sendParamByte = paramStr.toString().getBytes("iso8859_1");
			con.setRequestProperty("Content-length", String.valueOf(sendParamByte.length));
			DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
			dataOut.write(sendParamByte);
			dataOut.flush();
			dataOut.close();
			rspContent = new StringBuffer();
			in = new DataInputStream(con.getInputStream());
			int size = 0;
			FileOutputStream  fos = new FileOutputStream(fileSavePath);
			byte[] buf = new byte[BUFFER_SIZE];
			while ((size = in.read(buf)) != -1){
				fos.write(buf, 0, size);
			}
			fos.close();


		} catch (Exception e) {
			e.printStackTrace();
		 
		} finally {
			if (in != null)
				in.close();
		}


	}

	public String getSendEncode() {
		return sendEncode;
	}

	public void setSendEncode(String sendEncode) {
		this.sendEncode = sendEncode;
	}

	public String getReceiceEncode() {
		return receiceEncode;
	}

	public void setReceiceEncode(String receiceEncode) {
		this.receiceEncode = receiceEncode;
	}


public String getUrl() {
	return url;
}
public void setUrl(String url) {
	this.url = url;
}
public Map getParameters() {
	return parameters;
}
public void setParameters(Map parameters) {
	this.parameters = parameters;
}

public static void main(String[] args) throws Exception {
	HttpClient client=new HttpClient();
	//client.setProxy("10.100.11.148", "909");//设置代理
	client.setUrl("http://114.251.229.193:9001/sfss/sfac/update.jsp?step=2&user=sunshine&fileName=data%2Fyglife%2Fproduct%2F0061.dat");
	//client.addParameter("msg", "1");
	client.postAndDownFile("C://N22//TEST//test.dat");
	

}
	

}
